

// 评论模块的 路由  

var express = require("express")
var router = express.Router()
var {aesDecrypt,checkSession} = require('../utils')
var {MovieModel,CommentModel} = require("../utils/model")
var moment = require("moment")
router.get("/test",(req,res)=>{
    res.send("test for the comment ")
})


router.get('/mdetail',(req,res)=>{
    checkSession(req,res,username=>{
        var {mid} = req.query;
        MovieModel.findOne({
            id:mid
        }).then(result=>{
            res.render("mdetail",{
                username,
                result
            })
        })
    })
})


// 提交评论

router.post("/submit",(req,res)=>{
    var {mid} = req.query;
    var body = req.body; 
    console.log(body)
    checkSession(req,res,username=>{
        MovieModel.findOne({
            id:mid
        }).then(movie=>{
            body.time = moment().format("YYYY-MM-DD HH:mm:ss")
            body.movie = movie;
            body.author = username
            body.mid = mid 
            CommentModel.insertMany(body)
            .then(result=>{
                // res.send("评论提交成功...")  
                res.redirect("/comment/mlist")
            })
        })
    })
})



// 评论列表

router.get("/mlist",(req,res)=>{
    checkSession(req,res,username=>{
        // 分页查询  
        var page = req.query.page * 1 || 1;
        var pageSize = req.query.pageSize * 1  || 15 
        var total = 0;
        var totalPage = 0; 

        CommentModel.find({},{})
        .then(data=>{
            total = data.length;
            totalPage = Math.ceil(total/pageSize) 

            page = page<1 ? 1:page;
            page = page>totalPage ? totalPage :page  
            if(total>0){
                CommentModel.find({},{})
                .skip((page-1)*pageSize)
                .limit(pageSize)
                .sort({_id:-1})
                .then(result=>{
                    result = result.map((item)=>{
                        item = {...item._doc,time: moment(item.time).format("YYYY-MM-DD HH:mm:ss") }                 
                        return item;
                    })
                    res.render("mlist",{
                        username,
                        result,
                        page,
                        pageSize,
                        total,
                        totalPage
                    })
                })
            }else{
                res.render("mlist",{
                    username,
                    result:[],
                    page,
                    pageSize,
                    total,
                    totalPage
                })
            }
            
        })


        // 查询  
        // CommentModel.find({},{})
        // .sort({_id:-1})
        // .then(result=>{
        //         result = result.map((item)=>{
        //             console.log(moment(item.time).format("YYYY-MM-DD HH:mm:ss"))   
        //             item.time =  moment(item.time).format("YYYY-MM-DD HH:mm:ss")       
        //             console.log(item)                    
        //             return item;
        //         })

        //     res.render("mlist",{username,result})
        // })


        
    })
})


// 评论详情
router.get("/detail",(req,res)=>{
    checkSession(req,res,username=>{
        const {_id } = req.query;
        CommentModel.findOne({
            _id:_id
        }).then(result=>{
            result = {...result._doc,time:moment(result.time).format("YYYY-MM-DD HH:mm:ss") }
            res.render("detail",{
                username,
                result:result.movie,
                data:result,
            })
        })
    })
})

// 用户的评论列表

router.get("/plist",(req,res)=>{
    checkSession(req,res,username=>{
        const {author} = req.query;
        CommentModel.find({
            author
        })
        .sort({_id:-1})
        .then(result=>{
            result = result.map((item)=>{ 
                return {...item._doc,time: moment(item.time).format("YYYY-MM-DD HH:mm:ss") }  
            })
            res.render("plist",{
                username,
                author,
                result
            })
        })
    })
})


// 当前电影的评论列表
router.get("/mvdetail",(req,res)=>{
    checkSession(req,res,username=>{
        const {mid} = req.query;
        CommentModel.find({
            mid:mid,
        })
        .sort({_id:-1})
        .then(result=>{
            result = result.map((item)=>{ 
                return {...item._doc,time: moment(item.time).format("YYYY-MM-DD HH:mm:ss") }  
            })
            res.render("mvdetail",{
                username,
                result,
                movie:result[0].movie,
            })
        })
    })
})


// 删除评论
router.post("/delonecomment",(req,res)=>{
    checkSession(req,res,username=>{
        const {_id} = req.body;
        CommentModel.remove({
            _id
        }).then(result=>{
            res.json({
                code:200,
                result,
                type:1,
                msg:"删除成功"
            })
        })
    })
})


// 修改评论
router.post("/updateonecomment",(req,res)=>{
    checkSession(req,res,username=>{
        const {_id,title,content} = req.body;
        CommentModel.updateMany({
            _id
        },{
            $set:{
                title,
                content,
                time:new Date()
            }
        }).then(result=>{
            res.json({
                code:200,
                result,
                type:1,
                msg:"修改成功"
            })
        })
    })
})


router.get("/chat",(req,res)=>{
    checkSession(req,res,username=>{
        res.render("chat",{
            username
        })
    })
})


var multiparty = require("multiparty")
var fs = require("fs")
// 上传图片  
router.post("/uploadImg",(req,res)=>{
    const form = new multiparty.Form();  // 自定义表单对象  
    form.encoding = "utf-8"
    form.uploadDir = "./uploadtemp"  // 临时文件中转站
    form.maxFilesSize = 8*1024*1024;  // 8M 
    form.parse(req,function(err,fields,files){
        if(err) {
            console.log(err)
            res.send("<script>alert('图片过大,请重新上传');location.href='/movie'</script>")
        }
        var uploadUrl = "/images/upload/",
        file  = files['filedata'], // 图片信息
        originalFilename = file[0].originalFilename, // 文件名  zkl.jpg 
        tempath = file[0].path;
        var timestamp = new Date().getTime(); // 时间戳  为了避免图片名字冲突 
        uploadUrl += timestamp+originalFilename;  // zkl.jpg ==> 15112341231zkl.jpg
        var newPath = "./public"+uploadUrl;  // 最后路径 
        var fileRead = fs.createReadStream(tempath);  // 可读流 
        var fileWrite = fs.createWriteStream(newPath);  // 可写流  
        fileRead.pipe(fileWrite);
        fileWrite.on("close",()=>{
            fs.unlinkSync(tempath);  // 上传成功把中转站的文件删除 
            res.json({
                err:"",
                msg:uploadUrl
            })
        })
    })
})
module.exports = router;